package wxapp

import (
    "time"
	"os"
	"io"
	"wxsdk/wxpay/core"
)

func WritetoFile(filePath string, content []byte) error {
	fl, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		return err
	}
	defer fl.Close()
	n, err := fl.Write(content)
	if err != nil {
		return err
	}
	if err == nil && n < len(content) { //ErrShortWrite琛ㄧず鍐欏叆鐨勬暟鎹瘮鎻愪緵鐨勫皯锛屽嵈娌℃湁鏄惧紡鐨勯敊璇?
		err = io.ErrShortWrite
	}
	return nil
}


type DownloadBillRequest struct {
	Appid      string   `xml:"appid"`                 //微信分配的小程序ID
	MchId      string   `xml:"mch_id"`                //商户号
	SubAppid   string   `xml:"sub_appid,omitempty"`   //小程序的APPID,当前调起支付的小程序APPID(服务商特有参数)
	SubMchId   string   `xml:"sub_mch_id,omitempty"`  //微信支付分配的子商户号(服务商特有参数)
	DeviceInfo string   `xml:"device_info,omitempty"` //设备号
	NonceStr   string   `xml:"nonce_str"`             //随机字符串
	Sign       string   `xml:"sign"`                  //签名
	SignType   string   `xml:"sign_type,omitempty"`   //签名类型
	BillDate   string   `xml:"bill_date"`             //对账单日期
	BillType   string   `xml:"bill_type"`             //账单类型
	TarType    string   `xml:"tar_type,omitempty"`    //压缩账单
	RequestXML string   `xml:"-"`                     //最终请求串
}


func  DownloadBill(appId,mchId,subAppid,subMchId,appSecret string) error{
	client := core.GetWxPayClient(appId,mchId,appSecret,nil)
	var req = new(DownloadBillRequest)
	if len(subAppid) > 0 {
	   req.SubAppid = subAppid
	}
	if len(subMchId) > 0 {
	   req.SubMchId = subMchId
	}
	req.BillDate = time.Now().Format("20060102")
	req.BillType =  "ALL"
	req.TarType =  "GZIP"
	body, err := client.ExcuteFile(DownloadBillUrl, req)
    if err != nil {
		return err
	}
	filePath := "bill.gzip"
	WritetoFile(filePath, body)
	return nil
}
